﻿using LY.Entity;
using LY.Entity.Entities;
using LY.Entity.Jsons;
using LY.Entity.PageSearch;
using LY.Entity.SearchEntity;
using LY.Interface;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LY.Common.Utils;
using System.Text;
using System.IO;
using LY.Common.Utils.Sf_Struct;
using System.Net;
using System.Web.Script.Serialization;
using LY.Common.Utils.Sign;
using System.Configuration;
using LY.ShengPayApi.Model;

namespace QJ.CMS.Areas.Admin.Controllers
{
    public class T_ProjectController : Controller
    {
        // GET: /Project/
        private IT_ProjectService _pservice;
        private IInvestService _iservice;
        S_User loginUser = null;
        private IDocumentService _documentService;
        private IT_RepaymentPlanService _repaymentService;
        private IMemberService _member;
        private ICompanyService _company;

        private static string _sftAddress = ConfigurationManager.AppSettings["SftAddress"];
        private static string _merchantNo = ConfigurationManager.AppSettings["merchantNo"];
        private static string _backAddress = ConfigurationManager.AppSettings["BackAddress"];
        private static string _rechargeAddress = ConfigurationManager.AppSettings["RechargeAddress"];
        private static string _apiAddress = ConfigurationManager.AppSettings["ApiAddress"];
        private static string _zqFee = ConfigurationManager.AppSettings["ZQFee"];

        public T_ProjectController(IT_ProjectService pService, IInvestService iService, IDocumentService document, IT_RepaymentPlanService repaymentService, IMemberService member, ICompanyService company)
        {
            _pservice = pService;
            _iservice = iService;
            _documentService = document;
            _repaymentService = repaymentService;
            _member = member;
            _company = company;

            if (System.Web.HttpContext.Current.Session["LoginUseInfo"] != null)
            {
                loginUser = (S_User)System.Web.HttpContext.Current.Session["LoginUseInfo"];
            }
            else
            {
                loginUser = new S_User();
            }
        }

        #region 债权列表
        public ActionResult Project()
        {
            return View();
        }

        //债权列表搜索
        [HttpPost]
        public JsonResult ProjectList(T_ProjectSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            PagedList<T_Project_EX> pList = _pservice.QueryProjectList(search, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<T_Project_EX>(pList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }

        //查看
        public ActionResult ProjectDetail(int? id)
        {
            T_Project_EX project = null;
            T_ProjectSearch search = new T_ProjectSearch();
            if (id.HasValue)
            {
                project = _pservice.GetProject(id.Value);
                if (project != null)
                {
                    if (string.IsNullOrEmpty(project.EFPhotoPath))
                    {
                        project.EFPhotoPath = @"../../assets/img/noimg.jpg";
                    }
                    //List<T_Enterprise> list = _pservice.GetEnterpriseList(project.EnterpriseID);
                    ViewBag.RelevantList = _pservice.GetRelevantList(id);
                    ViewBag.EnterpriseName = _company.GetModel((int)project.EnterpriseID).CompanyName;
                }
                List<T_Document> documentlist = _documentService.GetDocumentList(id);//获取图片
                ViewBag.Document = documentlist;
            }
            else
            {
                project = new T_Project_EX();
                string parjectno = _pservice.GetProjectNo();
                if (!string.IsNullOrEmpty(parjectno))
                {
                    string LYdate = "LY" + DateTime.Now.ToString("yyyyMMdd");
                    int no = int.Parse(parjectno.Substring(parjectno.Length - 3, 3));
                    if (no > 0 && no < 10)
                    {
                        no++;
                        if (no != 10)
                        {
                            project.ProjectNo = LYdate + "00" + no;
                        }
                        else
                        {
                            project.ProjectNo = LYdate + "0" + no;
                        }
                    }
                    else if (no >= 10 && no <= 99)
                    {
                        no++;
                        if (no != 100)
                        {
                            project.ProjectNo = LYdate + "0" + no;
                        }
                        else
                        {
                            project.ProjectNo = LYdate + no;
                        }
                    }
                    else
                    {
                        project.ProjectNo = LYdate + no;
                    }
                }
                else
                {
                    project.ProjectNo = "LY" + DateTime.Now.ToString("yyyyMMdd") + "001";
                }
            }
            return View(project);
        }

        //编辑,新增
        public ActionResult ProjectEdit(int? id)
        {
            T_Project_EX project = null;
            ProjectSearch search = new ProjectSearch();
            if (id.HasValue)
            {
                project = _pservice.GetProject(id.Value);
                if (project != null)
                {
                    if (string.IsNullOrEmpty(project.EFPhotoPath))
                    {
                        project.EFPhotoPath = @"../../assets/img/noimg.jpg";
                    }
                    //ViewBag.RelevantList = _pservice.GetRelevantList(id); 这里没用到？
                    U_Company company = _company.GetModel((int)project.EnterpriseID);
                    if (company != null)
                    {
                        ViewBag.EnterpriseName = company.CompanyName;
                    }
                    else
                    {
                        ViewBag.EnterpriseName = "";
                    }
                }
                List<T_Document> Documentlist = _documentService.GetDocumentList(id);//获取图片
                ViewBag.Document = Documentlist;
            }
            else //新增
            {
                project = new T_Project_EX();
                //string parjectno = _pservice.GetProjectNo();//获取项目标号
                //if (!string.IsNullOrEmpty(parjectno))
                //{
                //    string LYdate = "QJZQ" + DateTime.Now.ToString("yyyyMMdd");
                //    int no = int.Parse(parjectno.Substring(parjectno.Length - 3, 3));
                //    if (no > 0 && no < 10)
                //    {
                //        no++;
                //        if (no != 10)
                //        {
                //            project.ProjectNo = LYdate + "00" + no;
                //        }
                //        else
                //        {
                //            project.ProjectNo = LYdate + "0" + no;
                //        }
                //    }
                //    else if (no >= 10 && no <= 99)
                //    {
                //        no++;
                //        if (no != 100)
                //        {
                //            project.ProjectNo = LYdate + "0" + no;
                //        }
                //        else
                //        {
                //            project.ProjectNo = LYdate + no;
                //        }
                //    }
                //    else
                //    {
                //        project.ProjectNo = LYdate + no;
                //    }
                //}
                //else
                //{
                //    project.ProjectNo = "QJZQ" + DateTime.Now.ToString("yyyyMMdd") + "001";
                //}
            }
            return View(project);
        }

        //保存项目
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ProjectSave(int? id, int? Eid, int? wid, int? rid, string TitlePic, string EFPhotographs, T_WindControlInformation windconinfo, T_RelevantDocument relement, string EFPhotoPath, T_Project project, FormCollection collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                string errmsg = "";
                string eFPhotoPaths = Request.Form["EFPhotoPath"];
                string eFPhotoExplain = Request.Form["EFPhotoExplains"];
                if (Eid.HasValue)
                {
                    project.EnterpriseID = Eid;
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "请选择企业！";
                    return Json(rMsg);
                }

                if (!Validate(project, out errmsg))
                {
                    rMsg.Status = -1;
                    rMsg.Message = errmsg;
                    return Json(rMsg);
                }
                if (wid.HasValue)
                {
                    windconinfo.ID = Convert.ToInt32(wid);
                }
                if (rid.HasValue)
                {
                    relement.ID = Convert.ToInt32(rid);
                }

                if (id == 0)
                {

                    project.CreateUser = loginUser.LoginName;
                    project.CreateTime = DateTime.Now;
                }

                project.AuditStatus = 0;
                project.AnnualisedRates = project.AnnualisedRates / 100;//转化成小数
                project.AddAnnualisedRates = project.AddAnnualisedRates / 100;//转化成小数
                //没有附加利率 为0
                if (project.AddAnnualisedRates == null)
                {
                    project.AddAnnualisedRates = 0;
                }
                //这里调用一下方法，生成一下标号
                string fenbiaoprojectNo = _pservice.CreadteProjectNo(project);
                project.ProjectNo = fenbiaoprojectNo;
                int ret = _pservice.SaveProject(project, windconinfo, relement, eFPhotoPaths, eFPhotoExplain);
                int retRePlan = 0;

                if (id == 0)
                {
                    //不拆标
                    if (project.SubProject == 0)
                    {
                        switch (project.DurationMonthOrDay)
                        {
                            case 1: //月
                                double? CurrentPrincipalA = Convert.ToDouble(project.TotalLoan) / 12 * (project.AnnualisedRates + project.AddAnnualisedRates);
                                for (int i = 0; i < project.ProjectDuration; i++)
                                {
                                    string RepaymentPlanNO = GetNo() + "-" + (i + 1).ToString();
                                    if (i != project.ProjectDuration - 1)
                                    {
                                        retRePlan = _pservice.SaveRepaymentPlan(ret, RepaymentPlanNO, CurrentPrincipalA, project.TotalLoan);
                                    }
                                    else
                                    {
                                        retRePlan = _pservice.SaveRepaymentPlan(ret, RepaymentPlanNO, Convert.ToDouble(project.TotalLoan) + CurrentPrincipalA, 0);
                                    }
                                }
                                break;
                            case 2: //日
                                DateTime dat1 = DateTime.Parse(DateTime.Now.Year + "-01-01");
                                DateTime dat2 = dat1.AddYears(1);
                                TimeSpan spanTime = (dat2 - dat1);

                                double? CurrentPrincipalB = Convert.ToDouble(project.TotalLoan) / spanTime.Days * (project.AnnualisedRates + project.AddAnnualisedRates) * project.ProjectDuration;
                                string RepaymentPlanNOA = GetNo();
                                retRePlan = _pservice.SaveRepaymentPlan(ret, RepaymentPlanNOA, Convert.ToDouble(project.TotalLoan) + CurrentPrincipalB, 0);
                                break;
                        }
                    }
                    else //拆标
                    {
                        //分标金额
                        double eachSubProAmt = (double)project.EachSubProjectAmount;//获取每个子标的金额
                        double iii = Convert.ToDouble(project.TotalLoan) / eachSubProAmt;//获取分几个子标
                        string projectName = project.ProjectName;
                        for (int ii = 0; ii < iii; ii++)
                        {
                            if (iii > 1)
                            {
                                project.ProjectName = projectName + "(第" + (ii + 1).ToString() + "标)";
                                project.ProjectNo = fenbiaoprojectNo + "_" + (ii + 1).ToString();
                            }
                            else
                            {
                                project.ProjectNo = fenbiaoprojectNo;
                            }
                            project.ParentProjectID = ret;
                            project.TotalLoan = (decimal)eachSubProAmt;
                            project.EachSubProjectAmount = 0;
                            int rett = _pservice.SaveProject(project, windconinfo, relement, eFPhotoPaths, eFPhotoExplain);//保存子标
                            switch (project.DurationMonthOrDay)
                            {
                                case 1: //按照月
                                    double? CurrentPrincipalA = eachSubProAmt / 12 * (project.AnnualisedRates + project.AddAnnualisedRates);
                                    for (int i = 0; i < project.ProjectDuration; i++)
                                    {
                                        string RepaymentPlanNO = GetNo() + "-" + (i + 1).ToString();
                                        if (i != project.ProjectDuration - 1)
                                        {
                                            retRePlan = _pservice.SaveRepaymentPlan(rett, RepaymentPlanNO, CurrentPrincipalA, (decimal)eachSubProAmt);
                                        }
                                        else
                                        {
                                            retRePlan = _pservice.SaveRepaymentPlan(rett, RepaymentPlanNO, eachSubProAmt + CurrentPrincipalA, 0);
                                        }
                                    }
                                    break;
                                case 2: //按照天
                                    DateTime dat1 = DateTime.Parse(DateTime.Now.Year + "-01-01");
                                    DateTime dat2 = dat1.AddYears(1);
                                    TimeSpan spanTime = (dat2 - dat1);

                                    double? CurrentPrincipalB = eachSubProAmt / spanTime.Days * (project.AnnualisedRates + project.AddAnnualisedRates) * project.ProjectDuration;
                                    string RepaymentPlanNOA = GetNo();
                                    retRePlan = _pservice.SaveRepaymentPlan(rett, RepaymentPlanNOA, eachSubProAmt + CurrentPrincipalB, 0);
                                    break;
                            }
                        }
                        double dd = Convert.ToDouble(project.TotalLoan) % (double)eachSubProAmt;
                        if (dd > 0)
                        {
                            project.ProjectNo = fenbiaoprojectNo; ;
                            project.ParentProjectID = ret;
                            int rettt = _pservice.SaveProject(project, windconinfo, relement, eFPhotoPaths, eFPhotoExplain);
                            switch (project.DurationMonthOrDay)
                            {
                                case 1:
                                    double? CurrentPrincipalA = dd / 12 * (project.AnnualisedRates + project.AddAnnualisedRates);
                                    for (int i = 0; i < project.ProjectDuration; i++)
                                    {
                                        string RepaymentPlanNO = GetNo() + "-" + (i + 1).ToString();
                                        if (i != project.ProjectDuration - 1)
                                        {
                                            retRePlan = _pservice.SaveRepaymentPlan(rettt, RepaymentPlanNO, CurrentPrincipalA, (decimal)dd);
                                        }
                                        else
                                        {
                                            retRePlan = _pservice.SaveRepaymentPlan(rettt, RepaymentPlanNO, dd + CurrentPrincipalA, 0);
                                        }
                                    }
                                    break;
                                case 2:
                                    DateTime dat1 = DateTime.Parse(DateTime.Now.Year + "-01-01");
                                    DateTime dat2 = dat1.AddYears(1);
                                    TimeSpan spanTime = (dat2 - dat1);

                                    double? CurrentPrincipalB = dd / spanTime.Days * (project.AnnualisedRates + project.AddAnnualisedRates) * project.ProjectDuration;
                                    string RepaymentPlanNOA = GetNo();
                                    retRePlan = _pservice.SaveRepaymentPlan(rettt, RepaymentPlanNOA, dd + CurrentPrincipalB, 0);
                                    break;
                            }
                        }
                    }
                }
                if (ret > 0)
                {
                    T_Document img = new T_Document();
                    if (project.ID == 0)
                    {
                        img.ProjectId = ret;
                    }
                    else
                    {
                        img.ProjectId = project.ID;
                    }
                    img.DocPath = collection["hid_pic"];
                    AddImages(img);


                    return RedirectToAction("Project", "T_Project");
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        //查询企业名称
        public ActionResult CompanyIndex(int? id)
        {
            return View();
        }

        //企业列表
        [HttpPost]
        public JsonResult CompanyList(CompanySearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            PagedList<U_Company_EX> pList = _company.QueryCompany_EXList(search, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<U_Company_EX>(pList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }

        
        #endregion

        #region 债权标审核
        //债权审核列表
        public ActionResult ProjectAuditList()
        {
            return View();
        }

        //债权审核列表
        [HttpPost]
        public JsonResult ProjectAuditList(T_ProjectSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            PagedList<T_Project_EX> pList = _pservice.QueryProjectList(search, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<T_Project_EX>(pList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }

        //审核页面
        public ActionResult ProjectAudit(int? id)
        {
            T_Project_EX project = null;
            ProjectSearch search = new ProjectSearch();
            if (id.HasValue)
            {
                project = _pservice.GetProject(id.Value);
                if (project != null)
                {
                    if (string.IsNullOrEmpty(project.EFPhotoPath))
                    {
                        project.EFPhotoPath = @"../../assets/img/noimg.jpg";
                    }
                    //List<T_Enterprise> list = _pservice.GetEnterpriseList(project.EnterpriseID);
                    //ViewBag.RelevantList = _pservice.GetRelevantList(id);
                    ViewBag.EnterpriseName = _company.GetModel((int)project.EnterpriseID).CompanyName;
                    ViewBag.LoginUser = loginUser.UserName;
                }
            }
            List<T_Document> documentlist = _documentService.GetDocumentList(id);//获取图片
            ViewBag.Document = documentlist;
            return View(project);
        }

        //审核
        [HttpPost]
        public int Audit(int? id, string name, int? status, string Audit)
        {
            int ret = -1;
            //这里调用盛付通的发标接口
            T_Project project = _pservice.GetModel((int)id);
            if (project.SubProject == 1) //表示是有子标或者是子标
            {
                List<T_Project> childProjectList = _pservice.QueryChildProjectList((int)id);//查询出该标的子标
                foreach (var child in childProjectList)
                {
                    if (!FaBiao(child))
                    {
                        return 0;
                    }
                    ret = _pservice.ChangeAudit(child.ID, name, status, Audit);//给每个子项目也修改审核状态
                }
            }
            else
            {
                if (!FaBiao(project))
                {
                    return 0;
                }
            }
            if (id.HasValue && status.HasValue)
            {
                ret = _pservice.ChangeAudit(id, name, status, Audit);
            }
            return ret;
        }

        //发标
        public bool FaBiao(T_Project project)
        {
            string name = project.LoanUser;
            string[] mysign = new string[9];
            mysign[0] = "merchantNo=" + _merchantNo;
            mysign[1] = "issueBidNo=" + project.ProjectNo;//标号 不会重复
            mysign[2] = "issueBidType=1";//发标类型 目前只能是1 应为如果是商户发标的话 就要一个商户号了，而现在的测试商户号 不能作为发标的商户号
            mysign[3] = "debitUserName=" + name;//这里发债权标的时候，都是已商户的名义发的，但是目前位置只能发个人标
            mysign[4] = "debitAmount=" + ((decimal)project.TotalLoan).ToString("0.00");//借款总金额
            mysign[5] = "revenueRate=" + ((double)(project.AnnualisedRates + project.AddAnnualisedRates) * 100).ToString("0.00");//年化收益率
            string deadline = "";//借款日期
            if (project.DurationMonthOrDay == 1)
            {
                deadline = (30 * project.ProjectDuration).ToString();
            }
            else if (project.DurationMonthOrDay == 2)
            {
                deadline = project.ProjectDuration.ToString();
            }
            mysign[6] = "deadline=" + deadline;
            mysign[7] = "rewardAmount=0.00";            //酬劳金额
            mysign[8] = "repaymentMode=2";//还款方式 按月付息，到期还本
            Array array = mysign;
            Array.Sort(array);
            string sign = string.Join("&", mysign);
            MySign mySign = new MySign();
            string temp = mySign.GetSign(sign);
            string newsign = Server.UrlEncode(temp);
            WebClient webClient = new WebClient();//p2pBid/{merchantNo}-{issueBidNo}
            //webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header，如果改为GET方式的话就去掉这句话即可  
            // 要提交表单的URI字符串。
            string postString = "?issueBidType=1&debitUserName=" + name + "&debitAmount=" + project.TotalLoan.ToString() +
                "&revenueRate=" + ((double)(project.AnnualisedRates + project.AddAnnualisedRates) * 100).ToString("0.00") + "&deadline=" + deadline + "&rewardAmount=0.00" +
                "&repaymentMode=2" + "&sign=" + newsign;
            byte[] postData = Encoding.UTF8.GetBytes(postString);//编码，尤其是汉字，事先要看下抓取网页的编码方式
            string url = _apiAddress + "/p2pBid/" + _merchantNo + "-" + project.ProjectNo + postString;
            byte[] responseData;
            try
            {
                responseData = webClient.UploadData(url, "PUT", postData);//得到返回字符流 
            }
            catch (Exception ex)
            {
                return false;
            }
            string strJson = Encoding.UTF8.GetString(responseData);
            if (strJson.Contains("请求成功完成"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public int ReturnBack(int projectid)
        {
            T_Project project = _pservice.GetModel(projectid);
            project.AuditStatus = 1;
            return _pservice.SaveModel(project);
        }

        #endregion

        #region 债权标流标
        public ActionResult LiuBiao(string projectid)
        {
            T_Project project = _pservice.GetModel(int.Parse(projectid));
            if (project.TenderStatus == 1 || project.TenderStatus == 2) //已满标或者已流标
            {
                return Json("{\"errorCode\":\"100\",\"errorMessage\":\"已满标或者已流标\"}");
            }
            string url = _backAddress + "/Pay/LiuBiaoNotifyUrl";
            string result = LY.ShengPayApi.Services.Put.PutP2PBidEvent(_merchantNo, project.ProjectNo, 1, url, "0.00", _apiAddress);
            if (result.Contains("请求成功完成"))
            {
                project.TenderStatus = 2;
                project.TenderTime = DateTime.Now;
                _pservice.SaveModel(project);
            }
            return Json(result);
        }
        #endregion

        #region 标放款
        //标放款页面
        public ActionResult ProjectLoanList()
        {
            return View();
        }

        //项目放款列表
        [HttpPost]
        public JsonResult ProjectLoanList(T_ProjectSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];

            PagedList<T_Project_EX> pList = _pservice.QueryProjectList(search, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<T_Project_EX>(pList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }

        //放款处理，即调用满标接口
        public ActionResult ProjectLoan(int id)
        {
            T_Project project = _pservice.GetModel(id);
            string notifyUrl = _backAddress + "/Pay/ManBiaoNotifyUrl";
            if (project.TenderStatus == 1 || project.LoanStatus == 0 ) //满标状态为1 放款状态为0 就执行满标接口
            {
                try
                {
                    string strJson = LY.ShengPayApi.Services.Put.PutP2PBidEvent(_merchantNo, project.ProjectNo, 2, notifyUrl, "0.00", _apiAddress);
                    if (strJson.Contains("请求成功完成"))
                    {
                        project.LoanStatus = 1;
                        _pservice.SaveModel(project);
                    }
                    return Json(strJson);
                }
                catch (Exception ex)
                {
                    return Json("{\"errorCode\":\"50\",\"errorMessage\":\"调用接口出错，请被恶心到了程序员来来解决吧\"}");
                }
            }
            return Json("{\"errorCode\":\"100\",\"errorMessage\":\"不满足放款的条件，tenderstatus不为1或loanstatus不为0\"}");
        }

        #endregion

        #region 投资列表
        //****投资列表信息*******//
        public ActionResult Invesment(int? id,int? status)
        {
            ViewBag.ID = id;
            ViewBag.Status = status;
            return View();
        }

        [HttpPost]
        public JsonResult InvesmentList(int? id, int? status, ProjectSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            PagedList<T_Investment_EX> pList = _pservice.QueryInvestmentList(id, status, search, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<T_Investment_EX>(pList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }

        //****编辑 新增 投资信息*******//
        public ActionResult InvesmentEdit(int? id)
        {

            T_Investment invest = null;
            if (id.HasValue)
            {
                invest = _pservice.GetInvesment(id.Value);
            }
            else
            {
                invest = new T_Investment();
            }
            return View(invest);
        }


        [HttpPost]
        public JsonResult InvesmentSave(int? id, T_Investment invest, FormCollection collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                string errmsg = "";
                if (!Validate(invest, out errmsg))
                {
                    rMsg.Status = -1;
                    rMsg.Message = errmsg;
                    return Json(rMsg);
                }
                if (id == 0)
                {
                    invest.CreateUser = "system";
                    invest.CreateTime = DateTime.Now;
                }

                int ret = _pservice.SaveInvestment(invest);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Data = ret;
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        //*****删除***//

        [HttpPost]
        public ActionResult InvesmentDelete(int id, FormCollection collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                if (id <= 0)
                {
                    rMsg.Status = -1;
                    rMsg.Message = "参数错误！";
                    return Json(rMsg);
                }
                int ret = _pservice.DeleteInvestment(id);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Data = ret;
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        private static bool Validate(T_Investment invest, out string errmsg)
        {
            errmsg = "";
            if (invest == null)
            {
                errmsg = "参数错误！";
                return false;
            }
            if (invest.ProjectId <= 0)
            {
                errmsg = "请选择投资项目！";
                return false;
            }
            return true;
        }

        #endregion

        #region 债权标还款
        //债权还款
        public ActionResult ToBeRepaymentList()
        {
            return View();
        }

        //待还款列表
        [HttpPost]
        public JsonResult ToBeRepaymentList1(ProjectSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            PagedList<T_RepaymentPlan_EX> pList = _pservice.QueryToBeRepaymentPlanList(search, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<T_RepaymentPlan_EX>(pList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }

        //债权还款明细列表页面
        public ActionResult RepaymentDetail(int id, int pid)
        {
            T_Project_EX project = _pservice.GetProject(pid);//根据pid查询出投资这个标的标号
            ViewBag.ProjectNo = project.ProjectNo;//发标号
            ViewBag.RepaymentUserName = project.RepaymentUser;
            ViewBag.RepaymentPlanId = id;
            T_RepaymentPlan repaymentPlan = _repaymentService.GetModel(id);
            ViewBag.repaymentNo = repaymentPlan.RepaymentPlanNO;
            List<T_Investment_EX> repaymentList = _iservice.QueryInvestmentList(Convert.ToInt32(pid), id);
            string transferItems = "";
            double repaymentAmount = 0.00;
            foreach (var item in repaymentList)
            {
                double temp = Math.Round(item.Profit, 2);
                repaymentAmount += temp;
                if (Convert.ToDouble(_zqFee) > 0.00)
                {
                    double zqFee = Convert.ToDouble(_zqFee);
                    double hehe = Math.Round(temp * zqFee, 2);
                    //盛付通接口应改成 member.SFTUserName;
                    transferItems += _member.getMemberInfo(item.MemberId).SFTUserName + ":" + (temp - hehe).ToString("0.00") + ":" + hehe.ToString("0.00") + ":1,";
                }
                else
                {
                    //盛付通接口应改成 member.SFTUserName;
                    transferItems += _member.getMemberInfo(item.MemberId).SFTUserName + ":" + temp.ToString("0.00") + ":0.00:1,";
                }
            }
            ViewBag.repaymentAmount = repaymentAmount.ToString("0.00");
            ViewBag.transferItems = transferItems.Substring(0, transferItems.Length - 1);
            ViewBag.sftAddress = _sftAddress;
            ViewBag.merchantNo = _merchantNo;
            ViewBag.backAddress = _backAddress;
            return View();
        }

        //项目还款明细列表
        [HttpPost]
        public JsonResult RepaymentDetailList1(int id, int projectid, string name, ProjectSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];

            PagedList<T_Investment_EX> pList = _iservice.GetInvestmentList(id, projectid, search, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<T_Investment_EX>(pList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }
        #endregion

        #region 盛付通Web个人还款接口
        public ActionResult WebRepayment(string repaymentPlanId, string projectId)
        {
            MySign mysign = new MySign();
            string strOrigin = Request["sign"];
            Array array = strOrigin.Split('|');
            string time = DateTime.Now.ToString("yyyyMMddHHmmss");
            Array.Sort(array);
            string tmp = "";
            for (int i = 0; i < array.Length; i++)
            {
                if (((string[])(array))[i].Contains("timestamp"))//替换时间
                {
                    ((string[])(array))[i] = ((string[])(array))[i].Replace("temp", time);
                }
                tmp += ((string[])(array))[i] + "&";
            }
            tmp = tmp.Substring(0, tmp.Length - 1);
            return Content(time + mysign.GetSign(tmp));
        }

        //还款的同步返回
        public ActionResult Repaymentcallback() //项目还款计划表T_RepaymentPlan 的Id,项目Id,
        {
            //验证签名
            string quertString = "" + "errorCode=" + Request["errorCode"] + "&errorMessage=" + Request["errorMessage"] +
                "&issueBidNo=" + Request["issueBidNo"] + "&repaymentNo=" + Request["repaymentNo"] + "&timestamp=" + Request["timestamp"];
            ViewBag.errorCode = Request["errorCode"];
            ViewBag.errorMessage = Request["errorMessage"];
            ViewBag.issueBidNo = Request["issueBidNo"];
            ViewBag.repaymentNo = Request["repaymentNo"];
            MySign mysign = new MySign();
            bool result = mysign.ValidateSign(quertString, Request["sign"]);
            if (result)
            {
                ViewBag.hehe = "验证数据正确";
            }
            else
            {
                ViewBag.hehe = "验证数据失败";
            }
            return View();
        }

        #endregion

        #region 子项目
        //子项目
        public ActionResult PetProject(int? id)
        {
            return View();
        }

        [HttpPost]
        public JsonResult PetProjectList(int? id, ProjectSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            PagedList<T_Project> pList = _pservice.QueryProjectList(id, search, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<T_Project>(pList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }
        #endregion

        #region 上传图片到本地
        public static List<ReturnParameters> rlist = new List<ReturnParameters>();
        [HttpPost]
        public ActionResult UpLoadProcess(UploadParameters para)
        {
            ReturnParameters path = new ReturnParameters();
            ActionResult json = new UploadImages("Upload", new string[]{ "",
                "Upload/pic_correlation",
                "Upload/pic_place",
                "Upload/pic_ tracking",
                "Upload/pic_compact",
                "Upload/pic_credentials",
                "Upload/pic_other"
            }).UpLoadProcess(para, ref path);

            rlist.Add(path);

            return json;

        }

        //添加图片
        private int AddImages(T_Document img)
        {
            List<T_Document> imgList = new List<T_Document>();
            int result = 0;
            if (rlist.Count > 0)
            {
                //string[] arr = img.DocPath.Remove(img.DocPath.LastIndexOf(',')).Split(',');
                foreach (var item in rlist)//遍历容器
                {
                    T_Document newimg = new T_Document();

                    newimg.Type = item.type;

                    newimg.DocPath = item.filePath;

                    newimg.ProjectId = img.ProjectId;

                    imgList.Add(newimg);
                }
                result = _documentService.AddImagesTodb(imgList);
            }
            return result;
        }

        public JsonResult DeleteImages(string id)
        {
            JsonSMsg msg = new JsonSMsg();
            int result = _documentService.DeleteImages(int.Parse(id));

            if (result > 0)
            {
                msg.Status = 1;

                msg.Message = "操作成功！";

            }
            else
            {
                msg.Status = -1;
                msg.Message = "操作失败！";
            }

            return Json(msg);

        }

        #endregion


        public ActionResult RepayPres(int? id)
        {
            T_Project_EX project = null;
            ProjectSearch search = new ProjectSearch();
            if (id.HasValue)
            {
                project = _pservice.GetProject(id.Value);
            }
            else
            {
                project = new T_Project_EX();
                string parjectno = _pservice.GetProjectNo();
            }


            return View(project);
        }

        

        [HttpPost]
        [ValidateInput(false)]
        public JsonResult RepayPresSave(int? id, T_Project_EX project, FormCollection collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                if (id == 0)
                {
                    project.CreateUser = "system";
                    project.CreateTime = DateTime.Now;
                }
                int ret = _pservice.SaveProject(project);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Data = ret;
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }


        [HttpPost]
        public int Loan(int? id, string name)
        {
            int ret = -1;
            if (id.HasValue)
            {
                ret = _pservice.ChangeLoan(id, name);
            }
            return ret;
        }



        [HttpPost]
        public JsonResult RelementPlanList(int? id, ProjectSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];

            PagedList<T_RepaymentPlan_EX> pList = _pservice.QueryRepaymentPlanList(id, search, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<T_RepaymentPlan_EX>(pList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }

        #region 还款列表
        //还款列表
        public ActionResult RepaymentList()
        {
            return View();
        }

        //还款列表
        [HttpPost]
        public JsonResult RepaymentLs(ProjectSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];

            PagedList<T_RepaymentPlan_EX> pList = _pservice.QueryRepaymentPlanList(search, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<T_RepaymentPlan_EX>(pList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }
        #endregion









        /// <summary>
        /// 项目还款
        /// </summary>
        /// <param name="id"></param>
        /// <param name="projectid"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        public int RepaymentNew(int? id, int? projectid, string name)//项目还款计划表T_RepaymentPlan 的Id,项目Id,
        {
            int ret = -1;
            if (id.HasValue)
            {
                ret = _pservice.GetRepmStatus(id.Value);//查询Status这一列的值
                if (ret == 1)
                {
                    return 10001;
                }
                if (ret == 3)
                {
                    return 10003;
                }
                if (ret == 2 && projectid.HasValue)//如果状态是2就表示要还款
                {
                    double CurrentPrincipal = _pservice.getRemainingPrincipal(id.Value);//查询剩余资金，sql语句写的是查询剩余资金，
                    if (CurrentPrincipal == 0)//但是这里的变量写的是当前资金？？？
                    {
                        ret = _iservice.SaveRept(projectid.Value, name, 0, 0);//这一步就是充值是利息
                        ret = _iservice.SaveReptPrincipal(projectid.Value, name, 0, 0);//这一步也是充值是本金
                        if (ret > 0)
                        {
                            ret = _pservice.ChangeRept(projectid.Value, name);//修改项目表T_Project的RepaymentStatus=1
                        }
                    }
                    else
                    {
                        ret = _iservice.SaveRept(projectid.Value, name, 0, 0);//还利息的时候就把利息存入到资金记录表，但是项目表不该
                    }
                    if (ret > 0)
                    {
                        ret = _pservice.RepaymentPlan(id.Value);//将还款记录表的状态改为3
                    }
                }
            }
            return ret;
        }

        /// <summary>
        /// 项目还款
        /// </summary>
        /// <param name="id"></param>
        /// <param name="projectid"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        public int Repayment(int? id, int? projectid, string name)
        {
            int ret = -1;
            if (id.HasValue)
            {
                ret = _pservice.GetRepmStatus(id.Value);
                if (ret == 1)
                {
                    return 10001;
                }
                if (ret == 3)
                {
                    return 10003;
                }
                if (ret == 2 && projectid.HasValue)
                {
                    List<T_Project> listp = _pservice.GetProjectList(projectid.Value);
                    double CurrentPrincipal = _pservice.getRemainingPrincipal(id.Value);
                    if (listp.Count > 0)
                    {
                        switch (listp[0].DurationMonthOrDay)
                        {
                            case 1:
                                List<T_FundsFlow> list = _pservice.getFundsList(projectid.Value);
                                if (list.Count > 0)
                                {
                                    for (int i = 0; i < list.Count; i++)
                                    {
                                        double? CurrentPrincipalA = Convert.ToDouble(list[i].OutPay) / 12 * listp[0].AnnualisedRates;
                                        if (CurrentPrincipal == 0)
                                        {
                                            ret = _pservice.SaveRept(projectid.Value, name, list[i].Id, list[i].MemberId, CurrentPrincipalA + Convert.ToDouble(list[i].OutPay));
                                            if (ret > 0)
                                            {
                                                ret = _pservice.ChangeRept(id, name);
                                            }
                                        }
                                        else
                                        {
                                            ret = _pservice.SaveRept(projectid.Value, name, list[i].Id, list[i].MemberId, CurrentPrincipalA);
                                        }
                                        if (ret > 0)
                                        {
                                            ret = _pservice.RepaymentPlan(id.Value);
                                        }
                                    }
                                }
                                break;
                            case 2:
                                DateTime dat1 = DateTime.Parse(DateTime.Now.Year + "-01-01");
                                DateTime dat2 = dat1.AddYears(1);
                                TimeSpan spanTime = (dat2 - dat1);

                                List<T_FundsFlow> listA = _pservice.getFundsList(projectid.Value);
                                if (listA.Count > 0)
                                {
                                    for (int i = 0; i < listA.Count; i++)
                                    {
                                        double? CurrentPrincipalB = Convert.ToDouble(listA[i].OutPay) / spanTime.Days * listp[0].AnnualisedRates * listp[0].ProjectDuration;
                                        if (CurrentPrincipal == 0)
                                        {
                                            ret = _pservice.SaveRept(projectid.Value, name, listA[i].Id, listA[i].MemberId, CurrentPrincipalB + Convert.ToDouble(listA[i].OutPay));
                                            if (ret > 0)
                                            {
                                                ret = _pservice.ChangeRept(id, name);
                                            }
                                        }
                                        else
                                        {
                                            ret = _pservice.SaveRept(projectid.Value, name, listA[i].Id, listA[i].MemberId, CurrentPrincipalB);
                                        }
                                        if (ret > 0)
                                        {
                                            ret = _pservice.RepaymentPlan(id.Value);
                                        }
                                    }
                                }
                                break;
                        }

                    }
                }
            }
            return ret;
        }





        /// <summary>
        /// 项目还款明细
        /// </summary>
        /// <param name="id"></param>
        /// <param name="projectid"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        public int RepaymentDetailList(int? id, int? projectid, string name)
        {
            int ret = -1;
            if (id.HasValue)
            {
                ret = _pservice.GetRepmStatus(id.Value);
                if (ret == 1)
                {
                    return 10001;
                }
                if (ret == 3)
                {
                    return 10003;
                }
                if (ret == 2 && projectid.HasValue)
                {
                    List<T_Project> listp = _pservice.GetProjectList(projectid.Value);
                    double CurrentPrincipal = _pservice.getRemainingPrincipal(id.Value);
                    if (listp.Count > 0)
                    {
                        switch (listp[0].DurationMonthOrDay)
                        {
                            case 1:
                                List<T_FundsFlow> list = _pservice.getFundsList(projectid.Value);
                                if (list.Count > 0)
                                {
                                    for (int i = 0; i < list.Count; i++)
                                    {
                                        double? CurrentPrincipalA = Convert.ToDouble(list[i].OutPay) / 12 * listp[0].AnnualisedRates;
                                        if (CurrentPrincipal == 0)
                                        {
                                            ret = _pservice.SaveRept(projectid.Value, name, list[i].Id, list[i].MemberId, CurrentPrincipalA + Convert.ToDouble(list[i].OutPay));
                                            if (ret > 0)
                                            {
                                                ret = _pservice.ChangeRept(id, name);
                                            }
                                        }
                                        else
                                        {
                                            ret = _pservice.SaveRept(projectid.Value, name, list[i].Id, list[i].MemberId, CurrentPrincipalA);
                                        }
                                        if (ret > 0)
                                        {
                                            ret = _pservice.RepaymentPlan(id.Value);
                                        }
                                    }
                                }
                                break;
                            case 2:
                                DateTime dat1 = DateTime.Parse(DateTime.Now.Year + "-01-01");
                                DateTime dat2 = dat1.AddYears(1);
                                TimeSpan spanTime = (dat2 - dat1);

                                List<T_FundsFlow> listA = _pservice.getFundsList(projectid.Value);
                                if (listA.Count > 0)
                                {
                                    for (int i = 0; i < listA.Count; i++)
                                    {
                                        double? CurrentPrincipalB = Convert.ToDouble(listA[i].OutPay) / spanTime.Days * listp[0].AnnualisedRates * listp[0].ProjectDuration;
                                        if (CurrentPrincipal == 0)
                                        {
                                            ret = _pservice.SaveRept(projectid.Value, name, listA[i].Id, listA[i].MemberId, CurrentPrincipalB + Convert.ToDouble(listA[i].OutPay));
                                            if (ret > 0)
                                            {
                                                ret = _pservice.ChangeRept(id, name);
                                            }
                                        }
                                        else
                                        {
                                            ret = _pservice.SaveRept(projectid.Value, name, listA[i].Id, listA[i].MemberId, CurrentPrincipalB);
                                        }
                                        if (ret > 0)
                                        {
                                            ret = _pservice.RepaymentPlan(id.Value);
                                        }
                                    }
                                }
                                break;
                        }

                    }
                }
            }
            return ret;
        }

        [HttpPost]
        public int Rept(int? id, string name)
        {
            int ret = -1;
            if (id.HasValue)
            {
                ret = _pservice.ChangeRept(id, name);
            }
            if (ret > 0)
            {
                List<T_Project> listp = _pservice.GetProjectList(id);
                if (listp.Count > 0)
                {
                    switch (listp[0].DurationMonthOrDay)
                    {
                        case 1:
                            List<T_FundsFlow> list = _pservice.getFundsList(id);
                            if (list.Count > 0)
                            {
                                for (int i = 0; i < list.Count; i++)
                                {
                                    if (listp[0].ProjectDuration != null)
                                    {
                                        for (int ii = 0; ii < listp[0].ProjectDuration; ii++)
                                        {
                                            double? CurrentPrincipalA = Convert.ToDouble(list[i].OutPay) / 12 * listp[0].AnnualisedRates;
                                            ret = _pservice.SaveRept(id, name, list[i].Id, list[i].MemberId, CurrentPrincipalA);
                                        }

                                    }
                                }
                            }
                            break;
                        case 2:
                            DateTime dtNow = DateTime.Now;

                            DateTime dat1 = DateTime.Parse(dtNow.Year + "-01-01");
                            DateTime dat2 = dat1.AddYears(1);
                            TimeSpan spanTime = (dat2 - dat1);


                            List<T_FundsFlow> listA = _pservice.getFundsList(id);
                            if (listA.Count > 0)
                            {
                                for (int i = 0; i < listA.Count; i++)
                                {
                                    double? CurrentPrincipalB = Convert.ToDouble(listA[i].OutPay) / spanTime.Days * listp[0].AnnualisedRates * listp[0].ProjectDuration;
                                    ret = _pservice.SaveRept(id, name, listA[i].Id, listA[i].MemberId, CurrentPrincipalB);
                                }
                            }
                            break;
                    }

                }
            }
            return ret;
        }



        private string getyyyyMMddNO(T_Project project)
        {
            //string RepaymentPlanNO = string.Empty;
            //string parjectno = _pservice.GetProjectNo();
            //if (!string.IsNullOrEmpty(parjectno))
            //{
            //    string LYdate = "LY" + DateTime.Now.ToString("yyyyMMdd");
            //    int no = int.Parse(parjectno.Substring(parjectno.Length - 3, 3));
            //    if (no > 0 && no < 10)
            //    {
            //        no++;
            //        if (no != 10)
            //        {
            //            RepaymentPlanNO = LYdate + "00" + no;
            //        }
            //        else
            //        {
            //            RepaymentPlanNO = LYdate + "0" + no;
            //        }
            //    }
            //    else if (no >= 10 && no <= 99)
            //    {
            //        no++;
            //        if (no != 100)
            //        {
            //            RepaymentPlanNO = LYdate + "0" + no;
            //        }
            //        else
            //        {
            //            RepaymentPlanNO = LYdate + no;
            //        }
            //    }
            //    else
            //    {
            //        RepaymentPlanNO = LYdate + no;
            //    }
            //}
            //else
            //{
            //    RepaymentPlanNO = "LY" + DateTime.Now.ToString("yyyyMMdd") + "001";
            //}
            //return parjectno;
            return _pservice.CreadteProjectNo(project);
        }

        private string GetNo()
        {
            string RepaymentPlanNO = string.Empty;
            string parjectno = _pservice.RepaymentPlanNO();
            if (!string.IsNullOrEmpty(parjectno))
            {
                string date = DateTime.Now.ToString("yyyyMMddHHmmss");
                int no;
                if (parjectno.Length == 19)//还款计划的No 如果最后是1-1 那么就要
                {
                    no = int.Parse(parjectno.Substring(parjectno.Length - 5, 3));
                }
                else
                {
                    no = int.Parse(parjectno.Substring(parjectno.Length - 3, 3));
                }
                if (no > 0 && no < 10)
                {
                    no++;
                    if (no != 10)
                    {
                        RepaymentPlanNO = date + "00" + no;
                    }
                    else
                    {
                        RepaymentPlanNO = date + "0" + no;
                    }
                }
                else if (no >= 10 && no <= 99)
                {
                    no++;
                    if (no != 100)
                    {
                        RepaymentPlanNO = date + "0" + no;
                    }
                    else
                    {
                        RepaymentPlanNO = date + no;
                    }
                }
                else
                {
                    RepaymentPlanNO = date + no;
                }
            }
            else
            {
                RepaymentPlanNO = DateTime.Now.ToString("yyyyMMddHHmmss") + "001";
            }
            return RepaymentPlanNO;
        }

        private static bool Validate(T_Project project, out string errmsg)
        {
            errmsg = "";
            if (project == null)
            {
                errmsg = "参数错误！";
                return false;
            }
            if (project.EnterpriseID <= 0)
            {
                errmsg = "请选择公司！";
                return false;
            }
            //if (!ValidateUtil.IsDecimal(project.AnnualisedRates.ToString()))
            //{
            //    errmsg = "年利化率格式有误！";
            //    return false;
            //}
            if (!ValidateUtil.IsDecimal(project.TotalLoan.ToString()))
            {
                errmsg = "借款总额格式有误！";
                return false;
            }
            return true;
        }










        [HttpPost]
        public ActionResult RelementDelete(int id, FormCollection collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                if (id <= 0)
                {
                    rMsg.Status = -1;
                    rMsg.Message = "参数错误！";
                    return Json(rMsg);
                }

                int ret = _pservice.DeleteRelement(id);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Data = ret;
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }



        /// <summary>
        /// 项目还款明细列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ProjectRepaymentDetail(int? id)
        {

            T_Project_EX project = null;
            ProjectSearch search = new ProjectSearch();
            if (id.HasValue)
            {
                project = _pservice.GetProject(id.Value);
                if (project != null)
                {
                    if (string.IsNullOrEmpty(project.EFPhotoPath))
                    {
                        project.EFPhotoPath = @"../../assets/img/noimg.jpg";
                    }
                    //List<T_Enterprise> list = _pservice.GetEnterpriseList(project.EnterpriseID);
                    ViewBag.RelevantList = _pservice.GetRelevantList(id);
                    //ViewBag.EnterpriseName = list[0].EnterpriseName;
                }
            }
            else
            {
                project = new T_Project_EX();
                string parjectno = _pservice.GetProjectNo();
                if (!string.IsNullOrEmpty(parjectno))
                {
                    string LYdate = "LY" + DateTime.Now.ToString("yyyyMMdd");
                    int no = int.Parse(parjectno.Substring(parjectno.Length - 3, 3));
                    if (no > 0 && no < 10)
                    {
                        no++;
                        if (no != 10)
                        {
                            project.ProjectNo = LYdate + "00" + no;
                        }
                        else
                        {
                            project.ProjectNo = LYdate + "0" + no;
                        }
                    }
                    else if (no >= 10 && no <= 99)
                    {
                        no++;
                        if (no != 100)
                        {
                            project.ProjectNo = LYdate + "0" + no;
                        }
                        else
                        {
                            project.ProjectNo = LYdate + no;
                        }
                    }
                    else
                    {
                        project.ProjectNo = LYdate + no;
                    }
                }
                else
                {
                    project.ProjectNo = "LY" + DateTime.Now.ToString("yyyyMMdd") + "001";
                }
            }


            return View(project);
        }



        //还款的签名GetRepaymentSign
        public ActionResult GetRepaymentSign()
        {
            string merchantNo = Request["merchantNo"];
            string timestamp = Request["timestamp"];
            string userName = Request["userName"];
            string origOrderType = Request["origOrderType"];
            string issueBidNo = Request["issueBidNo"];
            string repaymentNo = Request["repaymentNo"];
            string repaymentType = Request["repaymentType"];
            string repaymentAmount = Request["repaymentAmount"];
            string repaymentMode = Request["repaymentMode"];
            string isReward = Request["isReward"];
            string transferItems = Request["transferItems"];
            string callback = Request["callback"];
            string notifyUrl = Request["notifyUrl"];
            string sign = Request["sign"];

            string repaymentPlanId = Request["repaymentPlanId"];
            //查询剩余RemainingPrincipal是否是0 是不是最后一次了，最后一次还要加上本金还
            T_RepaymentPlan_EX repaymentPlan = _pservice.GetRepaymentPlanById(Convert.ToInt32(repaymentPlanId));
            //获得时间 
            timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
            int id = _pservice.SelectIdByProjectNo(issueBidNo);
            T_Project_EX project = _pservice.GetProject(id);
            //查询是投的月，还是天，月就是按月还，天就是最后一次性还
            double rate;
            if (project.DurationMonthOrDay == 1)//按月还
            {
                rate = (double)(project.AnnualisedRates + project.AddAnnualisedRates) / 12; //每个月的利息
            }
            else//一次性还
            {
                DateTime dat1 = DateTime.Parse(DateTime.Now.Year + "-01-01");
                DateTime dat2 = dat1.AddYears(1);
                TimeSpan spanTime = (dat2 - dat1);
                rate = (double)(project.AnnualisedRates + project.AddAnnualisedRates) * (double)project.ProjectDuration / spanTime.Days;
            }
            //查询这个标的投资人
            List<T_Investment_EX> list = _iservice.GetSftInvestment(id);
            //遍历这个list然后组成合适的字符会窜
            transferItems = "";
            decimal money = 0;
            for (int i = 0; i < list.Count; i++)
            {
                decimal temp;
                if (repaymentPlan.RemainingPrincipal == 0)
                {
                    temp = Math.Round(Convert.ToDecimal(list[i].amount * (decimal)rate), 2) + list[i].amount;
                }
                else
                {
                    temp = Math.Round(Convert.ToDecimal(list[i].amount * (decimal)rate), 2);
                }

                transferItems += list[i].userName + ":" + temp + ":" + list[i].platformFee + ":" + list[i].transferMode + ",";
                money += temp;
            }
            transferItems = transferItems.Substring(0, transferItems.Length - 1);
            repaymentAmount = money.ToString();

            string[] str = new string[13];
            str[0] = "merchantNo=" + merchantNo;
            str[1] = "timestamp=" + timestamp;
            str[2] = "userName=" + userName;
            str[3] = "origOrderType=" + origOrderType;
            str[4] = "issueBidNo=" + issueBidNo;
            str[5] = "repaymentNo=" + repaymentNo;
            str[6] = "repaymentType=" + repaymentType;
            str[7] = "repaymentAmount=" + repaymentAmount;
            str[8] = "repaymentMode=" + repaymentMode;
            str[9] = "isReward=" + isReward;
            str[10] = "transferItems=" + transferItems;
            str[11] = "callback=" + callback;
            str[12] = "notifyUrl=" + notifyUrl;

            Array array = str;
            Array.Sort(array);

            MySign mySign = new MySign();
            sign = mySign.GetSign(string.Join("&", str));

            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["timestamp"] = timestamp;
            dic["repaymentNo"] = repaymentNo;
            dic["repaymentAmount"] = repaymentAmount;
            dic["transferItems"] = transferItems;
            dic["sign"] = sign;

            JavaScriptSerializer serialize = new JavaScriptSerializer();

            return Content(serialize.Serialize(dic));

        }






    }
}
